import { Component, createEffect, createSignal } from 'solid-js';
import { useParams } from '@solidjs/router';
import { useCollectionStore } from './store';
import AppList from '@/components/AppList';
import { AppItem } from '@/types/app';
import { fetchCategoryApps } from '@/features/categories/store';

const CollectionDetail: Component = () => {
  const params = useParams();
  const { collections } = useCollectionStore();
  const [apps, setApps] = createSignal<AppItem[]>([]);
  const [loading, setLoading] = createSignal(true);

  createEffect(async () => {
    if (params.id) {
      setLoading(true);
      const collection = collections().find(c => c.id === params.id);
      if (collection) {
        try {
          const appPromises = collection.apps.map(async (app) => {
            const categoryApps = await fetchCategoryApps(app.Category);
            return categoryApps.find(categoryApp => categoryApp.pkgname === app.Pkgname);
          });
          const appResults = await Promise.all(appPromises);
          setApps(appResults.filter((app): app is AppItem => app !== undefined));
        } catch (error) {
          console.error('Failed to load collection apps:', error);
        } finally {
          setLoading(false);
        }
      }
    }
  });

  return (
    <div class="p-6 w-full h-full">
      <h1 class="text-2xl font-bold">
        {collections()?.find(c => c.id === params.id)?.name}
      </h1>
      <p class="text-gray-500 mb-6">
        {collections()?.find(c => c.id === params.id)?.description}
      </p>
      <AppList
        apps={apps()}
        loading={loading()}
      />
    </div>
  );
};

export default CollectionDetail;